package org.meb.speedway.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.meb.speedway.model.registry.Team;

public class TeamResolver {

	private List<Team> teams;
	private Map<String, Team> cache = new HashMap<String, Team>();

	public TeamResolver(List<Team> teams) {
		this.teams = teams;
	}

	public Team resolve(String teamName) {
		if (cache.containsKey(teamName)) {
			return cache.get(teamName);
		}
		
		String[] tokens = teamName.toLowerCase().split("\\ +");
		Team mostHitsTeam = null;
		int mostHits = 0;
		for (Team team : teams) {
			int hits = 0;
			for (String token : tokens) {
				if (team.getName().toLowerCase().contains(token)) {
					hits++;
				}
			}
			if (hits > mostHits) {
				mostHitsTeam = team;
				mostHits = hits;
			}
		}
		
		cache.put(teamName, mostHitsTeam);
		return mostHitsTeam;
	}
}
